﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;

using Hasiu.Entity;

namespace Hasiu.Service
{
    public class ConfigService
    {
        public static readonly ConfigService _ = new ConfigService();

        public List<AdminMenu> GetAdminMenuList()
        {
            var root = XElement.Load(HttpContext.Current.Server.MapPath("~/xml/adminMenu.xml"));
            var query = from p in root.Elements("menu")
                        select p;
            return query.Select(v => new AdminMenu
                                         {
                                             Id = Convert.ToInt32(v.Element("id").Value.Trim()),
                                             Pid = Convert.ToInt32(v.Element("pid").Value.Trim()),
                                             Name = v.Element("name").Value.Trim(),
                                             Icon = v.Element("icon").Value.Trim(),
                                             Url = v.Element("url").Value.Trim()
                                         }).ToList();
        }

        public AdminInfo GetAdminInfo()
        {
            AdminInfo adminInfo = null;
            const string xmlPath = "~/xml/siteConfig.xml";
            var root = XElement.Load(HttpContext.Current.Server.MapPath(xmlPath));
            var query = from p in root.Elements("adminInfo")
                        select p;
            foreach (var v in query)
            {
                adminInfo = new AdminInfo
                                {
                                    UserName = v.Element("userName").Value,
                                    Password = v.Element("password").Value
                                };
            }
            return adminInfo;
        }

        public void UpdateAdminInfo(AdminInfo adminInfo)
        {
            const string xmlPath = "~/xml/siteConfig.xml";
            var root = XElement.Load(HttpContext.Current.Server.MapPath(xmlPath));
            var query = from p in root.Elements("adminInfo")
                        select p;
            foreach (var v in query)
            {
                v.Element("userName").Value = adminInfo.UserName;
                v.Element("password").Value = adminInfo.Password;
            }
            root.Save(HttpContext.Current.Server.MapPath(xmlPath));
        }
    }
}
